import React, { PureComponent } from 'react';
import { message, Form, Input, Divider, Icon,Modal,Row,Col, Radio,Checkbox,Upload ,Button} from 'antd';
import { connect } from 'dva';
import token from '../../utils/token';
import {env, host} from '../../utils/request'
import SyOrderTableComponent from '../../components/SyOrderTableComponent';
import { SyOrderTableBasicFormComponent } from '../../components/SyOrderTableComponent';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const getBase64 = (file, callback) => {
  message.success(file.response.message)
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(file.originFileObj);
}

@Form.create()
@connect(state => ({
  modelState: state.product,
}))
export default class Product extends SyOrderTableComponent {

  // 缺省
  _initSortion = { sortField: 'id', sortOrder: 'desc', };
  _initPagination = { pageSize: 10, current: 1, };
  _initCriteriaQuery = { };
  _operator = [
    {
      needForm: false,
      needConfirm: true,
      buttonLabel: () => { if (this.state.statusQuery.state == 0) { return '上架' } else { return '下架' } },
      // okType: 'danger',
      buttonDisabled: 'none',
      confirmTitle: '确认 上架 / 下架？',
      handleEvent: () => {
        let needOnShelf = this.state.selectedRows.filter(entity => entity.state == 0).map(entity => entity.id);
        let needOffShelf = this.state.selectedRows.filter(entity => entity.state == 1).map(entity => entity.id);

        const { dispatch } = this.props;

        if (needOnShelf && needOnShelf.length > 0) {
          dispatch({
            type: this.state.baseModel + '/onShelf',
            payload: {
              ids: needOnShelf
            },
            callback: (code, msg) => {
              if (code == 200) {
                message.success(msg);
                this.resetCurrentForm();
                dispatch({
                  type: this.state.baseModel + '/fetch',
                  payload: {
                    ...this._initPagination,
                    ...this._initSortion,
                    ...this._initCriteriaQuery,
                    ...this.state.statusQuery,
                  }
                });
              } else {
                message.error(msg);
              }
            },
          });
        }

        if (needOffShelf && needOffShelf.length > 0) {
          dispatch({
            type: this.state.baseModel + '/offShelf',
            payload: {
              ids: needOffShelf
            },
            callback: (code, msg) => {
              if (code == 200) {
                message.success(msg);
                this.resetCurrentForm();
                dispatch({
                  type: this.state.baseModel + '/fetch',
                  payload: {
                    ...this._initPagination,
                    ...this._initSortion,
                    ...this._initCriteriaQuery,
                    ...this.state.statusQuery,
                  }
                });
              } else {
                message.error(msg);
              }
            },
          });
        }
      },
    },
    {
      needForm: true,
      buttonLabel: '批量导入SKU',
      modalTitle: '批量导入SKU',
      // buttonDisabled: 'none',
      onClickEvent: () => {
      },
      handleEvent: () => {
        const { dispatch } = this.props;
        const form = this.importSkuForm;
        form.validateFields((err, fieldsValue) => {
          if (err) return;
          dispatch({
            type: 'product/importProductBySku',
            payload: {
              skus: fieldsValue.skus,
            },
            callback: (code, msg) => {
              if (code == 200) {
                message.success(msg);
                this.resetCurrentForm();
                dispatch({
                  type: this.state.baseModel + '/fetch',
                  payload: {
                    ...this._initPagination,
                    ...this._initSortion,
                    ...this._initCriteriaQuery,
                    ...this.state.initPagination,
                    ...this.state.initSortion,
                    ...this.state.initCriteriaQuery,
                    queryUrl: this.state.queryUrl,
                  }
                });
              } else {
                message.error(msg);
              }
            },
          });
        });
      },
      renderForm: () => {
        const { modelState: { selectItems } } = this.props;
        const { editedEntity } = this.state;
        return (
          <SyOrderTableBasicFormComponent
            ref={(form) => {
              this.importSkuForm = form;
            }}
            formItems={this.importSkuItem}
            selectItems={selectItems}
            needInitValue={true}
            editedEntity={editedEntity}
          >
          </SyOrderTableBasicFormComponent>
        );
      },
    },
  ];

  importSkuItem = [
    {
      name: 'skus',
      label: 'SKU',
      placeholder: 'SKU',
      type: 'longString',
      rules: [{
        required: true, message: '请输入SKU',
      }],
    },
  ];

  initSelection() {
    const { dispatch } = this.props;
    // dispatch({
    //   type: 'systemUser/fetchSelectItems',
    //   payload: { apiUrl: '/system/organization', selectName: 'systemOrganizationSelectItems' }
    // });
   /* dispatch({
      type: 'product/fetchSelectItems',
      payload: { service: '/product', apiUrl: '/productCategory', selectName: 'catSelectItems', current: 1, pageSize: 1000 }
    });*/
  }

  componentWillMount() {
    this.initSelection();
    this.setState({
      baseModel: 'product',
      operator: this._operator,
      initPagination: this._initPagination,
      initSortion: this._initSortion,
      initCriteriaQuery: this._initCriteriaQuery,
      needSearch: true,
      needAdd: false,
      needEdit: true,
      needDelete: true,
      needTableColumnsOperator: true,
      needTableCheckbox: true,
      entityStatus: [{ name: '已上架', value: 1 }, { name: '已下架', value: 0 }, { name: '仓库中', value: undefined }],
      statusField: 'state',
      statusQuery: { state: 1 },
      tableBorder: false,
      tableScroll: { y: 800 },
      tableColumns: [
        {
          title: 'SKU',
          dataIndex: 'sku',
          width: 100,
        },
        {
          title: '商品',
          dataIndex: 'imagePath',
          width: 100,
          type: 'image',
        },
        {
          title: '价格',
          dataIndex: '2',
          // width: 180,
          // sorter: true,
          align: 'left',
          render: (text, record) => {
            return (
              <div>
                <span>
                  {record.name}
                </span>
                <Divider style={{ margin: 3 }} />
                <span>
                  {record.price ? ('¥ ' + record.price) : '/'}
                </span>
              </div>
            );
          },
        },
        {
          title: '类型',
          dataIndex: 'stage',
          width: 120,
          sorter: true,
          render: (text, record) => <span>{record.stage ? '分期商品' : '普通商品'}</span>,
        },
        {
          title: '访问量',
          dataIndex: '4',
          width: 160,
          render: (text, record) => {
            return (
              <div>
                <span>
                  访客数：<span style={{ color: '#e8e8e8' }}> / </span>
                </span>
                <Divider style={{ margin: 3 }} />
                <span>
                  浏览量：<span style={{ color: '#e8e8e8' }}> / </span>
                </span>
              </div>
            );
          },
        },
        {
          title: '库存',
          dataIndex: 'strogeCount',
          width: 100,
        },
        {
          title: '总销量',
          dataIndex: 'saleCount',
          width: 100,
        },
        {
          title: '创建时间',
          dataIndex: 'updateTime',
          width: 180,
        },
        {
          title: '首页推荐位',
          dataIndex: 'recommendOrder',
          width: 120,
          render: (text, record) => {
            return (
              <div
                onMouseEnter={(e) => {
                  record.showOrderEdit = true;
                  this.forceUpdate(() => { });
                }}
                onMouseLeave={(e) => {
                  record.showOrderEdit = false;
                  this.forceUpdate(() => { });
                }}
              >
                {
                  record.recommend ? (
                    <span>已推荐</span>
                  ) : (
                      <span style={{ color: '#e8e8e8', display: record.showOrderEdit ? 'none' : 'inline-block' }}> / </span>
                    )
                }
                <a style={{ marginLeft: record.recommend ? 12 : 0, display: record.showOrderEdit ? 'inline-block' : 'none' }}
                  onClick={() => {
                    let _url = record.recommend ? record.imagePath : ''
                    this.setState({
                      editedEntity: record,
                      imageUrl: _url,
                      isRecommend: record.recommend
                    })
                    this.handleModalVisible(true)
                  }}>
                  <Icon type="edit" />
                </a>
              </div>

            );
          },
        },
      ],
      searchFormItem: [
        {
          name: 'catId',
          label: '一级分类ID',
          placeholder: '一级分类ID',
          type: 'string',
        },
        {
          name: 'secondCatId',
          label: '二级分类ID',
          placeholder: '二级分类ID',
          type: 'string',
        },
        {
          name: 'thirdCatId',
          label: '三级分类ID',
          placeholder: '三级分类ID',
          type: 'string',
        },
        {
          name: 'sku',
          label: 'SKU',
          placeholder: 'SKU',
          type: 'string',
        },
      ],
      simpleAddFormItem: [
        {
          name: 'name',
          label: '商品名称',
          placeholder: '商品名称',
          type: 'string',
          rules: [{
            required: true, message: '请输入商品名称',
          }],
        },
        {
          name: 'price',
          label: '价格',
          placeholder: '价格',
          type: 'number',
          rules: [{
            required: true, message: '请输入商品价格',
          }],
        },
        {
          name: 'catId',
          label: '商品分类',
          placeholder: '商品分类',
          type: 'select',
          selectOption: { itemName: 'catSelectItems', name: 'name', value: 'id' },
          rules: [{
            required: true, message: '请选择商品分类',
          }],
        },
      ],
      simpleEditFormItem: [
        {
          name: 'name',
          label: '商品名称',
          placeholder: '商品名称',
          type: 'string',
          rules: [{
            required: true, message: '请输入商品名称',
          }],
        },
        {
          name: 'price',
          label: '价格',
          placeholder: '价格',
          type: 'number',
          rules: [{
            required: true, message: '请输入商品价格',
          }],
        },
      ],

      otherModal: this.renderRecommendModal,
      uploading: false,
      upModalVisiable: false,
      imageUrl:'',
      isRecommend:false
    });
  }



  handleModalVisible = (e) =>{
    this.setState({
      upModalVisiable: !!e,
    })
    if(!e){
      this.setState({
        uploading: false,
        imageUrl:'',
      })
    }
  }
  renderCheckBoxItem = () =>{
    let result = [],option = [
      {
        tit:'sdfz',
        val:'up',
      },
      // {
      //   tit:'想美',
      //   val:'xbeauty',
      // },
      // {
      //   tit:'信花花',
      //   val:'xflower',
      // },
      // {
      //   tit:'有点',
      //   val:'upoint',
      // },

    ];

    if(option.length >0){
      option.map((item,index) =>{
        const _obj ={label:'',value: '',key:''};
        _obj.label = item.tit;
        _obj.value = item.val;
        _obj.key = index;
        result.push(_obj);
      })
    }
    return result
  }
  uploadChange =  (info) => {
    console.log(info)
    if (info.file.status === 'uploading') {
      this.setState({ uploading: true });
    }
    if (info.file.status === 'done') {
      getBase64(info.file, imageUrl => this.setState({
       imageUrl: imageUrl,
        uploading: false,
      }));
    }
  }
  handleEditRecommend = e => {
    console.log(this.state.isRecommend)
    e.preventDefault();
    const { dispatch, form } = this.props;
    const {imageUrl,isRecommend,editedEntity} = this.state
    form.validateFields((err, fieldsValue) => {
      if (err) return;
       console.log(fieldsValue)
      let _param = {
        id: editedEntity.id,
        imagePath: '',
        isRecommend:isRecommend,
        sources:'',
      }
      if(isRecommend && !fieldsValue.imagePath && !imageUrl){
        message.error('请上传图片');
        return
      } else if(isRecommend   && !fieldsValue.imagePath && imageUrl){
        _param.imagePath = imageUrl
      } else if(isRecommend && fieldsValue.imagePath){
        _param.imagePath = fieldsValue.imagePath.file.response.data;
      }
      if(fieldsValue.sources.length ==0){
        message.error('请选择产品类型')
        return
      }else {
          _param.sources = fieldsValue.sources.join(',')
      }
      console.log(_param);
      console.log(this.props)
      dispatch({
        type: 'product/fetchRecommendProduct',
        payload:{..._param},
        callback: (res) =>{
          this.handleModalVisible(false)
          message.success(res.message);
          dispatch({
            type: this.state.baseModel + '/fetch',
            payload: {
              ...this._initPagination,
              ...this._initSortion,
              ...this._initCriteriaQuery,
              ...this.state.statusQuery,
            }
          });
        }
      });

    });
  };
  handleFormReset = () => {
    console.log('ss')

  };
  handleRadioChange = (e) =>{
    console.log( e.target.value)
    this.setState({
      isRecommend: e.target.value,
    });
  }

  renderRecommendModal =() =>{
    const {upModalVisiable,editedEntity,uploading,isRecommend} = this.state
    const {form} =this.props
    const _wrapperCol = {
      xs: { span: 24 },
      sm: { span: 24 },
      md: { span: 24 },
    };
    const uploadButton = (
      <div>
        <Icon type={uploading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    const  imageUrl = this.state.imageUrl
    return (
      <Modal
        title="推广编辑"
        visible={upModalVisiable}
        footer={null}
        closable = {false}
        onCancel={() => this.handleModalVisible(false)}
        afterClose={() => {form.resetFields()}}
      >
        <Form layout="inline" onSubmit={this.handleEditRecommend}  >
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col  {..._wrapperCol} style={{marginBottom:20}}>
              <FormItem  label="首页推荐位">
                {form.getFieldDecorator('isRecommend', {
                  initialValue: editedEntity.recommend,
                })(<RadioGroup onChange={this.handleRadioChange} >
                  <Radio value={false}>否</Radio>
                  <Radio value={true}>是</Radio>
                </RadioGroup>)}
              </FormItem>
            </Col>
            {
              isRecommend ?
                <Col  {..._wrapperCol} style={{marginBottom:20}}>
                  <FormItem label='推荐图片' >
                    {form.getFieldDecorator('imagePath', {})( <Upload
                      listType="picture-card"
                      style={{width:60,height:60}}
                      showUploadList={false}
                      action={host[env] + '/user/creditMarket/upload/'}
                      headers ={{ Authorization: token.get(),}}
                      onChange={this.uploadChange}
                    >
                      {imageUrl ? <img  style={{width:60,height:60}} src={imageUrl} alt="avatar" /> : uploadButton}
                    </Upload>)
                    }
                  </FormItem>
                </Col>: ''
            }

            <Col  {..._wrapperCol} style={{marginBottom:20}}>
              <FormItem  label="产品类型">
                {form.getFieldDecorator('sources', {
                  initialValue: editedEntity.recommendSourceList,
                })(<CheckboxGroup options={this.renderCheckBoxItem()}  />)}
              </FormItem>
            </Col>

            <Col {..._wrapperCol}>
              <span>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
              </span>
            </Col>
          </Row>
        </Form>

      </Modal>
    )

  }


  constructor(props) {
    super(props);
  }

  componentDidMount() {
    super.componentDidMount();
  }

}
